<?php
/**
* 数据操作类
*/
class Db
{
    
    protected static $instance;//实例

    protected $link; //pdo链接对象

    protected $error = null; //错误信息

    protected $lastSql = ''; //最后执行的sql

    protected $table;

    protected $where = ' ';

    protected $cloumn = " * ";

    protected $order = " ";

    protected $limit = "";

    /**
     * [__construct pdo对象的生成]
     */
    public function __construct()
    {

        try {
            $this->link = @new PDO(config('db_type').":host=".config('db_host').";dbname=".config('db_name').";charset=".config('db_charset'),config('db_user'),config('db_pass'));
            
        } catch (PdoException $e) {
            $this->error = "数据链接失败,".$e->getMessage();
        }
    }
    /**
     * [getError 获取错误信息]
     * @return [type] [description]
     */
    public static function getError()
    {
        return self::$instance->error;
    }
    /**
     * [getLastsql 获取最后执行sql]
     * @return [type] [description]
     */
    public static function getLastsql()
    {
        return self::$instance->lastSql;
    }

    /**
     * [query 执行原生sql(查询)]
     * @param  [type] $sql [description]
     * @return [type]      [description]
     */
    public static function query($sql)
    {
        if(!self::$instance){
            self::$instance = new self();
        }

        if(self::$instance->error){
            return false;
        }
        // 1  链接数据 库
        // 
        
        self::$instance->lastSql = $sql;

        $res = self::$instance->link->query($sql);


        if(!$res){
            self::$instance->error = self::$instance->link->errorInfo();
            return false;
        }

        // // 2 把sql 发给数据 库
        $data = $res->fetchAll(PDO::FETCH_ASSOC);

        return $data;
        // 3 从结果集中取出数据 返回

    }
    /**
     * [exec 执行原生sql(增删改)]
     * @param  [type] $sql [description]
     * @return [type]      [description]
     */
    public static function exec($sql)
    {
        if(!self::$instance){
            self::$instance = new self();
        }

        self::$instance->lastSql = $sql;

        $res = self::$instance->link->exec($sql);

        if($res===false){
            self::$instance->error = self::$instance->link->errorInfo();
            return false;
        }

        return true;
        
        // 1  链接数据 库

        // 2 把sql 发给数据 库

        // 3 从结果集中取出数据 返回

    }

    public static function table($table)
    {

        if(!self::$instance){
           self::$instance = new self();
        }

        self::$instance->table = $table;

        return  self::$instance;
    }

    public function find()
    {
        
        $sql = "select ".$this->cloumn." from ".$this->table.$this->where.$this->order." limit 1";

       $res =  self::query($sql);

       if(is_array($res)){
            return current($res);
       }else{
            return $res;
       }
    }

    public function findAll()
    {
        $sql = "select ".$this->cloumn." from ".$this->table.$this->where.$this->order.$this->limit;

        $res =  self::query($sql);

        return $res;
    }

    public function where($where)
    {
        
        $this->where = " where ".$where;

        return $this;
    }

    public function cloumn($cloumn)
    {
        $this->cloumn = $cloumn;
        return $this;
    }

    public function order($order)
    {
        $this->order = " order by ".$order;
        return $this;
    }

    public function limit($limit)
    {
        $this->limit = " limit ".$limit;
        return $this;
    }
    /**
     * [delete 删除数据]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delete($id=null)
    {
        if($id){

            $key = $this->get_primary_key();

            $sql = "delete from ".$this->table." where ".$key." = ".$id;
            
        }else{

            $sql = "delete from ".$this->table.$this->where;
        }
        return self::exec($sql);
    }
    /**
     * [get_primary_key 获取主键]
     * @return [type] [description]
     */
    public function get_primary_key()
    {
        $sql = "desc ".$this->table;

        $data = self::query($sql);

        foreach ($data as $row) {
            if($row['Key']=='PRI'){
                return $row['Field'];
            }
        }
        return false;
    }

    public function insert($data)
    {

       $values = implode("','",$data);

       $keys = implode(',',array_keys($data));

       $sql =  "insert into ".$this->table." (".$keys.") values('".$values."')";

       return self::exec($sql);

    }

    public function update($data)
    {

        $str = '';
       foreach ($data as $k => $v) {
           $str .= $k ."='".$v."',";
       }

       $str = rtrim($str,',');

       $sql =  "update ".$this->table." set ".$str.$this->where;

       return self::exec($sql);

    }


}
